package arithmetic.multithread;
/**
 * 线程间通信方式二
 * @author lidd
 *
 */
public class Thread2 {

	public static void main(String[] args) {

		final Printer1 print = new Printer1();

		new Thread() {
			public void run() {
				while(true) {
					try {
						print.print1();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

		new Thread() {
			public void run() {
				while(true) {
					try {
						print.print2();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

		new Thread() {
			public void run() {
				while(true) {
					try {
						print.print3();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

}

class Printer1{
	private int flag = 1;

	public void print1() throws InterruptedException {
		synchronized(this) {
			while(flag != 1) {
				this.wait();
			}
			System.out.print("哈");
			System.out.print("哈");
			System.out.print("哈");
			System.out.print("哈");
			System.out.print("哈");
			System.out.print("哈");
			System.out.println("\r\n");
			flag = 2;
			this.notifyAll();
		}
	}

	public void print2() throws InterruptedException {
		synchronized(this) {
			while(flag != 2) {
				this.wait();
			}
			System.out.print("呵");
			System.out.print("呵");
			System.out.print("呵");
			System.out.print("呵");
			System.out.print("呵");
			System.out.print("呵");
			System.out.println("\r\n");
			flag = 3;
			this.notifyAll();
		}
	}

	public void print3() throws InterruptedException {
		synchronized(this) {
			while(flag != 3) {
				this.wait();
			}
			System.out.print("啦");
			System.out.print("啦");
			System.out.print("啦");
			System.out.print("啦");
			System.out.print("啦");
			System.out.print("啦");
			System.out.println("\r\n");
			flag = 1;
			this.notifyAll();
		}
	}
}